'use client';

import type React from 'react';
import axios from 'axios';
import { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Palette, Eraser, RotateCcw, Sparkles, Download, Brush, Wand2 } from 'lucide-react';

const colors = [
	'#000000',
	'#FF6B6B',
	'#4ECDC4',
	'#45B7D1',
	'#96CEB4',
	'#FFEAA7',
	'#DDA0DD',
	'#98D8C8',
	'#F7DC6F',
	'#BB8FCE',
	'#85C1E9',
	'#F8C471',
];

export default function DrawingApp() {
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const [isDrawing, setIsDrawing] = useState(false);
	const [currentColor, setCurrentColor] = useState('#000000');
	const [brushSize, setBrushSize] = useState(5);
	const [isEraser, setIsEraser] = useState(false);
	const [isGenerating, setIsGenerating] = useState(false);
	const [generatedImage, setGeneratedImage] = useState<string | null>(null);

	useEffect(() => {
		const canvas = canvasRef.current;
		if (!canvas) return;

		const ctx = canvas.getContext('2d');
		if (!ctx) return;

		// Set canvas size
		canvas.width = 800;
		canvas.height = 600;

		// Set white background
		ctx.fillStyle = '#ffffff';
		ctx.fillRect(0, 0, canvas.width, canvas.height);

		// Set drawing properties
		ctx.lineCap = 'round';
		ctx.lineJoin = 'round';
	}, []);

	const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
		setIsDrawing(true);
		draw(e);
	};

	const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
		if (!isDrawing) return;

		const canvas = canvasRef.current;
		if (!canvas) return;

		const ctx = canvas.getContext('2d');
		if (!ctx) return;

		const rect = canvas.getBoundingClientRect();
		const x = e.clientX - rect.left;
		const y = e.clientY - rect.top;

		ctx.lineWidth = brushSize;
		ctx.globalCompositeOperation = isEraser ? 'destination-out' : 'source-over';
		ctx.strokeStyle = currentColor;

		ctx.lineTo(x, y);
		ctx.stroke();
		ctx.beginPath();
		ctx.moveTo(x, y);
	};

	const stopDrawing = () => {
		setIsDrawing(false);
		const canvas = canvasRef.current;
		if (!canvas) return;
		const ctx = canvas.getContext('2d');
		if (!ctx) return;
		ctx.beginPath();
	};

	const clearCanvas = () => {
		const canvas = canvasRef.current;
		if (!canvas) return;
		const ctx = canvas.getContext('2d');
		if (!ctx) return;

		ctx.fillStyle = '#ffffff';
		ctx.fillRect(0, 0, canvas.width, canvas.height);
	};

	const generateArt = async () => {
		setIsGenerating(true);

		const canvas = canvasRef.current;
		if (!canvas) return;

		canvas.toBlob(async (blob) => {
			if (!blob) {
				console.error('图像转换失败');
				setIsGenerating(false);
				return;
			}

			const formData = new FormData();
			formData.append('image', blob, 'drawing.png');

			try {
				const res = await axios.post('/api/get_draw_result', formData, {
					headers: {
						'Content-Type': 'multipart/form-data',
					},
				});

				const resultImageUrl = res.data;
				console.log('AI Generated Image URL:', resultImageUrl);
				setGeneratedImage(resultImageUrl.result);
			} catch (error: any) {
				console.error('上传失败:', error.response?.data || error.message);
			} finally {
				setIsGenerating(false);
			}
		}, 'image/png');
	};

	const downloadImage = () => {
		const canvas = canvasRef.current;
		if (!canvas) return;

		const link = document.createElement('a');
		link.download = 'my-drawing.png';
		link.href = canvas.toDataURL();
		link.click();
	};

	if (generatedImage) {
		return (
			<div className='min-h-screen bg-gradient-to-br from-purple-50 via-pink-50 to-blue-50 p-4'>
				<div className='max-w-6xl mx-auto'>
					<div className='text-center mb-8'>
						<div className='inline-flex items-center gap-2 bg-white/80 backdrop-blur-sm rounded-full px-6 py-3 shadow-lg mb-4'>
							<Sparkles className='w-5 h-5 text-purple-600' />
							<span className='font-semibold text-gray-800'>AI 创作完成</span>
						</div>
						<h1 className='text-4xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent mb-2'>
							你的艺术作品
						</h1>
						<p className='text-gray-600'>AI 已将你的简笔画转换为精美的艺术作品</p>
					</div>

					<div className='grid lg:grid-cols-2 gap-8 items-start'>
						<Card className='p-6 bg-white/80 backdrop-blur-sm shadow-xl border-0'>
							<div className='flex items-center gap-2 mb-4'>
								<Brush className='w-5 h-5 text-gray-600' />
								<h3 className='font-semibold text-gray-800'>原始绘画</h3>
							</div>
							<div className='bg-white rounded-xl p-4 shadow-inner'>
								<canvas
									ref={canvasRef}
									className='border-2 border-gray-100 rounded-lg w-full h-auto max-w-full'
									style={{ maxHeight: '400px' }}
								/>
							</div>
						</Card>

						<Card className='p-6 bg-white/80 backdrop-blur-sm shadow-xl border-0'>
							<div className='flex items-center gap-2 mb-4'>
								<Wand2 className='w-5 h-5 text-purple-600' />
								<h3 className='font-semibold text-gray-800'>AI 生成作品</h3>
								<Badge className='bg-gradient-to-r from-purple-500 to-pink-500 text-white'>新作品</Badge>
							</div>
							<div className='bg-white rounded-xl p-4 shadow-inner'>
								<img
									src={generatedImage || '/placeholder.svg'}
									alt='AI Generated Art'
									className='w-full h-auto rounded-lg shadow-lg'
									style={{ maxHeight: '400px', objectFit: 'contain' }}
								/>
							</div>
						</Card>
					</div>

					<div className='flex justify-center gap-4 mt-8'>
						<Button
							onClick={() => {
								setGeneratedImage(null);
								clearCanvas();
							}}
							size='lg'
							className='bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white shadow-lg'>
							<Brush className='w-5 h-5 mr-2' />
							重新绘画
						</Button>
						<Button
							onClick={downloadImage}
							variant='outline'
							size='lg'
							className='border-2 border-purple-200 hover:bg-purple-50'>
							<Download className='w-5 h-5 mr-2' />
							下载原图
						</Button>
					</div>
				</div>
			</div>
		);
	}

	return (
		<div className='min-h-screen bg-gradient-to-br from-purple-50 via-pink-50 to-blue-50 p-4'>
			<div className='max-w-6xl mx-auto'>
				{/* Header */}
				<div className='text-center mb-8'>
					<div className='inline-flex items-center gap-2 bg-white/80 backdrop-blur-sm rounded-full px-6 py-3 shadow-lg mb-4'>
						<Palette className='w-5 h-5 text-purple-600' />
						<span className='font-semibold text-gray-800'>AI 绘画工坊</span>
					</div>
					<h1 className='text-4xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent mb-2'>
						释放你的创意
					</h1>
					<p className='text-gray-600'>简单几笔，AI 帮你创造艺术奇迹</p>
				</div>

				<div className='grid lg:grid-cols-4 gap-6'>
					{/* Tools Panel */}
					<div className='lg:col-span-1'>
						<Card className='p-6 bg-white/80 backdrop-blur-sm shadow-xl border-0 sticky top-4'>
							<h3 className='font-semibold text-gray-800 mb-4 flex items-center gap-2'>
								<Brush className='w-5 h-5' />
								绘画工具
							</h3>

							{/* Color Palette */}
							<div className='mb-6'>
								<label className='text-sm font-medium text-gray-700 mb-3 block'>颜色选择</label>
								<div className='grid grid-cols-4 gap-2'>
									{colors.map((color) => (
										<button
											key={color}
											onClick={() => {
												setCurrentColor(color);
												setIsEraser(false);
											}}
											className={`w-10 h-10 rounded-full border-2 transition-all duration-200 hover:scale-110 ${
												currentColor === color && !isEraser
													? 'border-gray-800 shadow-lg scale-110'
													: 'border-gray-200 hover:border-gray-400'
											}`}
											style={{ backgroundColor: color }}
										/>
									))}
								</div>
							</div>

							<Separator className='my-4' />

							{/* Brush Size */}
							<div className='mb-6'>
								<label className='text-sm font-medium text-gray-700 mb-3 block'>画笔大小: {brushSize}px</label>
								<Slider
									value={[brushSize]}
									onValueChange={(value) => setBrushSize(value[0])}
									max={20}
									min={1}
									step={1}
									className='w-full'
								/>
							</div>

							<Separator className='my-4' />

							{/* Tool Buttons */}
							<div className='space-y-3'>
								<Button
									onClick={() => setIsEraser(!isEraser)}
									variant={isEraser ? 'default' : 'outline'}
									className={`w-full justify-start ${
										isEraser
											? 'bg-orange-500 hover:bg-orange-600 text-white'
											: 'hover:bg-orange-50 hover:text-orange-600 hover:border-orange-200'
									}`}>
									<Eraser className='w-4 h-4 mr-2' />
									{isEraser ? '橡皮擦模式' : '橡皮擦'}
								</Button>

								<Button
									onClick={clearCanvas}
									variant='outline'
									className='w-full justify-start hover:bg-red-50 hover:text-red-600 hover:border-red-200'>
									<RotateCcw className='w-4 h-4 mr-2' />
									清空画板
								</Button>
							</div>
						</Card>
					</div>

					{/* Canvas Area */}
					<div className='lg:col-span-3'>
						<Card className='p-6 bg-white/80 backdrop-blur-sm shadow-xl border-0'>
							<div className='flex items-center justify-between mb-4'>
								<h3 className='font-semibold text-gray-800 flex items-center gap-2'>
									<Palette className='w-5 h-5' />
									创作画板
								</h3>
								<Badge
									variant='secondary'
									className='bg-purple-100 text-purple-700'>
									800 × 600
								</Badge>
							</div>

							{/* Canvas */}
							<div className='bg-white rounded-xl p-4 shadow-inner mb-6'>
								<canvas
									ref={canvasRef}
									onMouseDown={startDrawing}
									onMouseMove={draw}
									onMouseUp={stopDrawing}
									onMouseLeave={stopDrawing}
									className='border-2 border-dashed border-gray-200 rounded-lg cursor-crosshair w-full h-auto max-w-full hover:border-purple-300 transition-colors'
									style={{ maxHeight: '500px' }}
								/>
							</div>

							{/* Generate Button */}
							<div className='flex justify-center'>
								<Button
									onClick={generateArt}
									disabled={isGenerating}
									size='lg'
									className='bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white shadow-lg px-8 py-3 text-lg font-semibold'>
									{isGenerating ? (
										<>
											<div className='animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2' />
											AI 创作中...
										</>
									) : (
										<>
											<Sparkles className='w-5 h-5 mr-2' />
											生成艺术作品
										</>
									)}
								</Button>
							</div>

							{isGenerating && (
								<div className='mt-4 text-center'>
									<div className='inline-flex items-center gap-2 bg-purple-100 text-purple-700 px-4 py-2 rounded-full'>
										<div className='w-2 h-2 bg-purple-500 rounded-full animate-bounce' />
										<div
											className='w-2 h-2 bg-purple-500 rounded-full animate-bounce'
											style={{ animationDelay: '0.1s' }}
										/>
										<div
											className='w-2 h-2 bg-purple-500 rounded-full animate-bounce'
											style={{ animationDelay: '0.2s' }}
										/>
										<span className='ml-2 text-sm font-medium'>AI 正在分析你的创作...</span>
									</div>
								</div>
							)}
						</Card>
					</div>
				</div>
			</div>
		</div>
	);
}
